<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Config;

class Upload extends Controller
{
    public function index(Request $request)
    {
        $upload_path = ROOT_PATH.'public'.DS.Config::get('upload_path');
        if ($request->isPost()) {

            //判断是否是替换文件，有就删除
            if ($request->has('old')) {

                $file_path = ROOT_PATH.'public'.DS . $request->param('old');
                if (file_exists($file_path)) {
                    @unlink($file_path);
                }

            }

            $data = [
                'code' => 200,
                'url' => ''
            ];

            // 获取表单上传文件
            $files = request()->file('file');
            if ($files) {
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $files->move($upload_path);
                    if ($info) {
                        // 成功上传后 获取上传信息
                        $data['url'] = '/'.Config::get('upload_path').'/'.$info->getSaveName();

                    } else {
                        // 上传失败获取错误信息
                        $data['state'] = $files->getError();
                    }
            } else {
                $data['code'] = 400;
            }
            return json($data);
        } else {
            return return_json(1, '请求错误！');
        }
    }

    /*上传
* */
    public function upload_editor(Request $request)
    {
        $upload_path = ROOT_PATH.'public'.DS.Config::get('upload_path');
        if ($request->isPost()) {

            if ($request->has('old')) {

                $file_path = ROOT_PATH.'public'.DS . $request->param('old');
                if (file_exists($file_path)) {
                    @unlink($file_path);
                }

            }
            // 获取表单上传文件
            $file = $request->file('editormd-image-file');
            // 移动到框架应用根目录/public/uploads/ 目录下
            if ($file) {
                $info = $file->move($upload_path);
                if ($info) {
                    // 成功上传后 获取上传信息
                    $data['success'] = 1;
                    $data['message'] = '上传成功';
                    $data['url'] = '/'.Config::get('upload_path').'/'.$info->getSaveName();
                } else {
                    $data['success'] = 0;
                    $data['message'] = $file->getError();
                }
            } else {
                $data['success'] = 0;
                $data['message'] = '上传插件出BUG';
            }
            return json($data);
        } else {
//            $this->error('请求参数错误','index/welcome');
            return return_json(1, '请求错误！');
        }
    }
}
